//
//  UPSheZhiViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/18.
//

#import "UPSheZhiViewController.h"
#import "UPSheZhiItem.h"

@interface UPSheZhiViewController ()

@property (nonatomic, strong) UPSheZhiItem *goOutItem;
@property (nonatomic, strong) UPSheZhiItem *versionItem;
@property (nonatomic, strong) UPSheZhiItem *authCancleItem;
@property (nonatomic, strong) UPCustomAlertView *privacyAlertView;

@end

@implementation UPSheZhiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.bgImageView.image = [UIImage imageNamed:@"setup_bg"];
    self.title = LocalizableForKey(@"Set up");

    [self commonInitSubviews];
}

- (void)commonInitSubviews {
    [self.view addSubview:self.goOutItem];
    [self.view addSubview:self.versionItem];
    if ([AppConfig sharedInstance].appCountryEnv == AppCountryEnvIndonesia) {
        self.authCancleItem.hidden = YES;
    } else {
        self.authCancleItem.hidden = NO;
    }
    [self.view addSubview:self.authCancleItem];
    [self.goOutItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view).inset(25);
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(15);
        make.height.mas_equalTo(57);
    }];
    [self.versionItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(self.goOutItem);
        make.top.equalTo(self.goOutItem.mas_bottom).offset(15);
    }];
    [self.authCancleItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(self.versionItem);
        make.top.equalTo(self.versionItem.mas_bottom).offset(15);
    }];
}

- (UPSheZhiItem *)goOutItem {
    if (!_goOutItem) {
        _goOutItem = [[UPSheZhiItem alloc] initWithItemType:UPSetItemTypeA title:LocalizableForKey(@"Go Out") alpha:1.0];;
        [_goOutItem addTarget:self action:@selector(goOutAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _goOutItem;
}

- (UPSheZhiItem *)versionItem {
    if (!_versionItem) {
        _versionItem = [[UPSheZhiItem alloc] initWithItemType:UPSetItemTypeB title:LocalizableForKey(@"Version") alpha:1.0];;
        [_versionItem addTarget:self action:@selector(versionAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _versionItem;
}

- (UPSheZhiItem *)authCancleItem {
    if (!_authCancleItem) {
        _authCancleItem = [[UPSheZhiItem alloc] initWithItemType:UPSetItemTypeA title:LocalizableForKey(@"Account Cancellation") alpha:0.5];;
        [_authCancleItem addTarget:self action:@selector(authCancelAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _authCancleItem;
}

#pragma mark - 网络请求
- (void)fetchLogOut {
    [SVProgressHUD show];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchLoginOutWithCompletion:^(BOOL status, NSString * _Nullable msg) {
        if (status) {
            
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (void)fetchAccountCancel {
    [SVProgressHUD show];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchAccountCancelWithCompletion:^(BOOL status, NSString * _Nullable msg) {
        if (status) {
            
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

#pragma mark - Method
- (void)goOutAction:(UIButton *)button {
    [self showGoOutAlert];
}

- (void)versionAction:(UIButton *)button {
    [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@: %@", LocalizableForKey(@"Version"), @"1.0.0"]];
}

- (void)authCancelAction:(UIButton *)button {
    BOOL isReachable = [UPNetworkPermissionChecker isNetworkReachable];
    if (isReachable) {
        [self showAccountCancelAlert];
    } else {
        [self showNoNetWortAlert];
    }
}

- (void)showGoOutAlert {
    __block typeof(self) weakSelf = self;
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithBackgroundImage:[UIImage imageNamed:@"alert_bg_image1"] style:UPAlertViewStyleCenter];
    [alert setTitle:@"Exit app title" font:[UIFont boldSystemFontOfSize:13]];

    [alert setContent:LocalizableForKey(@"Exit app content") font:[UIFont systemFontOfSize:13]];
    
    [alert addButtonWithTitle:LocalizableForKey(@"Continue to use")
                        style:UPButtonStyleDefault
                      handler:^{
    }];

    [alert addButtonWithTitle:LocalizableForKey(@"Confirm Exit")
                        style:UPButtonStyleDestructive
                      handler:^{
        [weakSelf fetchLogOut];
    }];

    [alert showInView:self.view];
}

- (void)showAccountCancelAlert {
    
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithBackgroundImage:[UIImage imageNamed:@"alert_bg_image1"] style:UPAlertViewStyleCenter];
    alert.showPrivacy = YES;
    alert.isButtonClickDismiss = NO;
    __block typeof(self) weakSelf = self;
    alert.privacyTapBlock = ^{
        [weakSelf privacyItemClicked];
    };
    [alert setTitle:LocalizableForKey(@"Account cancellation?") font:[UIFont boldSystemFontOfSize:13]];

    [alert setContent:LocalizableForKey(@"Let you borrow without worry, hope youstay and enjoy more exclusive rights and interests.") font:[UIFont systemFontOfSize:13]];
    
    [alert addButtonWithTitle:LocalizableForKey(@"Delete")
                        style:UPButtonStyleDefault
                      handler:^{
        if (weakSelf.privacyAlertView.isPrivacySelected) {
            [weakSelf.privacyAlertView dismiss];
            [weakSelf fetchAccountCancel];
        } else {
            [UPProgressHUD showInfoWithStatus:LocalizableForKey(@"please aggree privacy")];
        }
    }];

    [alert addButtonWithTitle:LocalizableForKey(@"Stay")
                        style:UPButtonStyleDestructive
                      handler:^{
    }];

    [alert showInView:self.view];
    self.privacyAlertView = alert;
}

-(void)showNoNetWortAlert {
    // 1. 创建弹窗（标题设为nil隐藏标题）
    UIAlertController *alert = [UIAlertController
                                alertControllerWithTitle:nil
                                message:LocalizableForKey(@"network failed")
                                preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:LocalizableForKey(@"Stop")
                                   style:UIAlertActionStyleCancel
                                   handler:nil];
    [alert addAction:cancelAction];
    
    UIAlertAction *confirmAction = [UIAlertAction
                                    actionWithTitle:LocalizableForKey(@"Turning on")
                                    style:UIAlertActionStyleDefault
                                    handler:^(UIAlertAction * _Nonnull action) {
        
        upOpenAppSettings();
    }];
    
    [alert addAction:confirmAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)privacyItemClicked {
    NSString *url = [NSString stringWithFormat:@"%@%@", kH5Domain, @"reportform"];
    [self pushToWebViewController:url];
}

-(void)pushToWebViewController: (NSString *)url {
    
    UPWebViewController *webVC = [[UPWebViewController alloc] init];
    webVC.urlString = url;
    webVC.isFollowOrder = false;
    [[UIApplication up_currentViewController].navigationController pushViewController:webVC animated:YES];
}

@end
